package com.drivers.user.controller;

import com.drivers.model.Result;
import com.drivers.user.config.OSSFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.drivers.user.service.IFileService;
/**
 * 文件请求处理
 * 
 *
 */
@RestController
@RequestMapping("file")
public class FileController
{
    /** 字符常量：斜杠 {@code '/'} */
    public static final char SLASH = '/';

    /** 字符常量：反斜杠 {@code '\\'} */
    public static final char BACKSLASH = '\\';

    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private IFileService FileService;

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public Result<OSSFile> upload(MultipartFile file)
    {
        try
        {
            // 上传并返回访问地址
            String url = FileService.uploadFile(file);
            OSSFile ossFile = new OSSFile();
            ossFile.setName(getName(url));
            ossFile.setUrl(url);
            return Result.success(ossFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return Result.error( "上传失败");
        }
    }



    public static String getName(String filePath)
    {
        if (null == filePath)
        {
            return null;
        }
        int len = filePath.length();
        if (0 == len)
        {
            return filePath;
        }
        if (isFileSeparator(filePath.charAt(len - 1)))
        {
            // 以分隔符结尾的去掉结尾分隔符
            len--;
        }

        int begin = 0;
        char c;
        for (int i = len - 1; i > -1; i--)
        {
            c = filePath.charAt(i);
            if (isFileSeparator(c))
            {
                // 查找最后一个路径分隔符（/或者\）
                begin = i + 1;
                break;
            }
        }

        return filePath.substring(begin, len);
    }

    public static boolean isFileSeparator(char c)
    {
        return SLASH == c || BACKSLASH == c;
    }
}